#include "mod_eth.h"
#include "string.h"
#include "sys.h"

#include "data.h"
#include "platform.h"
#include <Net_Config.h>

extern uint8_t own_hw_adr[];

static void vTaskTCPnet(void *pvParameters)
{
    while(1){
		main_TcpNet();
		vTaskDelay(2);
    }
}

static void vTaskStart(void *pvParameters)
{
	TickType_t xLastWakeTime;
	const TickType_t xFrequency = 100;
	
	init_TcpNet ();
	
    xLastWakeTime = xTaskGetTickCount();
	
    while(1){	
		timer_tick();
        vTaskDelayUntil(&xLastWakeTime, xFrequency);
    }
}

int32_t init_tcp(void){
    
    uint32_t macset = data_getint("macset");
    if (macset == 0){
        struct ChipID chipid;
        get_chipid(&chipid);
        
        own_hw_adr[0] = 0;
        own_hw_adr[1] = *(uint8_t *)&chipid.id[1];
        own_hw_adr[2] = *((uint8_t *)&chipid.id[2]+3);
        own_hw_adr[3] = *((uint8_t *)&chipid.id[2]+2);
        own_hw_adr[4] = *((uint8_t *)&chipid.id[2]+1);
        own_hw_adr[5] = *((uint8_t *)&chipid.id[2]+0);    
    }else{
        char_t mac_str[20] = {0};
        data_getstr("mac", mac_str, sizeof(mac_str));

        int32_t mac_value[6];
        sscanf(mac_str, "%2x%2x%2x%2x%2x%2x", &mac_value[0],&mac_value[1],&mac_value[2],
                                          &mac_value[3],&mac_value[4],&mac_value[5]);	
        
        own_hw_adr[0] = (uint8_t)mac_value[0];
        own_hw_adr[1] = (uint8_t)mac_value[1];
        own_hw_adr[2] = (uint8_t)mac_value[2];
        own_hw_adr[3] = (uint8_t)mac_value[3];
        own_hw_adr[4] = (uint8_t)mac_value[4];
        own_hw_adr[5] = (uint8_t)mac_value[5];
    }

    printf("mac:%02x-%02x-%02x-%02x-%02x-%02x\r\n", own_hw_adr[0], own_hw_adr[1], own_hw_adr[2],own_hw_adr[3],own_hw_adr[4],own_hw_adr[5]);

    os_pthread_t xHandleTaskTCPnet;    
    os_pthread_t xHandleTaskStart;

    if (os_pthread_create("tcp_net", &xHandleTaskTCPnet, vTaskTCPnet, NULL,  OS_TASK_PRIO_HIGHT, OS_STACK_SIZE_LARGE) != 0){
        return -1;
    }
    
    
    if (os_pthread_create("tcp_tick", &xHandleTaskStart, vTaskStart, NULL,  OS_TASK_PRIO_REALTIME, OS_STACK_SIZE_LARGE) != 0){
        return -1;
    }
    return 0;
}
